import React, { useState, useEffect,useRef } from 'react'
import { Button, Table,Modal, Switch} from 'antd'
import axios from 'axios'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import UserForm from '../../../components/user-manager/UserForm'
const { confirm } = Modal


export default function UserList() {
    const [dataSource, setdataSource] = useState([])
    const [regionList, setregionList] = useState([])
    const [roleList, setroleList] = useState([])
    const [isVisible, setisVisible] = useState(false)
    const [isUpdateVisible, setisUpdateVisible] = useState(false)
    const [isUpdateDisabled, setisUpdateDisabled] = useState(false)
    const [curUpdate, setcurUpdate] = useState(null)
    const ref = useRef(null)
    const updateRef = useRef(null)
    const {username,roleId,region}= JSON.parse(localStorage.getItem("token"))
    useEffect(() => {
        const roleObj = {
            "1":"superadmin",
            "2":"admin",
            "3":"editor"
        }
        axios.get("/users?_expand=role").then(res => {
            const list = res.data
            setdataSource(roleObj[roleId]==="superadmin"?list:[
                ...list.filter(item=>item.username===username),
                ...list.filter(item=>item.region===region&& roleObj[item.roleId]==="editor")
            ])
        })
    }, [roleId,region,username])

    useEffect(() => {
        axios.get("/regions").then(res=>{
            setregionList(res.data)
        })
    
    }, [])

    useEffect(() => {
        axios.get("/roles").then(res=>setroleList(res.data))
    }, [])

    const columns = [
        {
            title: '区域',
            dataIndex: 'region',
            filters:[//注意，这里不解构就是一个二维数组了，不符合文档要求。     这里是下拉的筛选项。
                ...regionList.map(item=>({//返回的是一个对象，为了歧义，用括号包裹
                    text:item.title,
                    value:item.value    
                })
                    ),
                {
                    text:"全球",
                    value:"全球"
                }
            ],
            onFilter:(value,item)=>{//item是所有项，value是选中的筛选项
                if(value==="全球")
                    return item.region==="";
                    return item.region===value;
            },
            render: (region) => {
                return <b>{region===""?'全球':region}</b>
            }
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            render:(role)=>{
                return role?.roleName
            }
        },
        {
            title: "用户名",
            dataIndex: 'username'
        },
        {
            title: "用户状态",
            dataIndex: 'roleState',
            render:(roleState,item)=>{
                return <Switch checked={roleState} onChange={()=>{handleChange(item)}} disabled={item.default}></Switch>
            }
        },
        {
            title: "操作",
            render: (item) => {
                return <div>
                    <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => confirmMethod(item)} disabled={item.default}/>
                    <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.default} onClick={()=>handleUpdate(item)}/>
                </div>
            }
        }
    ];

    const confirmMethod = (item) => {
        confirm({
            title: '你确定要删除?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                deleteMethod(item)
            },
            onCancel() {
               
            },
        });

    }
    const addForm=()=>{
        ref.current.validateFields().then(data=>{
            ref.current.resetFields();//清空表单
            axios.post('/users',{
                ...data, 
                "roleState": true,
                "default": false,
            }).then(res=>{
                setdataSource([...dataSource,//修改显示后角色名称没有显示的bug
                    {...res.data,
                   role: roleList.filter(item=>data.roleId===item.id)[0]
                }
                ])
            })
        })
    }
    const deleteMethod = (item) => {
        setdataSource(dataSource.filter(data=>
            data.id!==item.id
        ))
        axios.delete(`/users/${item.id}`)
    }
    const handleOk=()=>{
        setisVisible(false);
        addForm();
    }
    const handleCancel=()=>{
        setisVisible(false)
    }
    const handleChange=(item)=>{//开关处理
        item.roleState=!item.roleState;
        setdataSource([...dataSource,item])
        axios.patch(`/users/${item.id}`,{
            roleState:item.roleState
        })
    }
    const handleUpdate=(item)=>{//操作按钮的回调
        setTimeout(() => {
            setisUpdateVisible(true);
            setcurUpdate(item,console.log(1));
            if(item.roleId===1){        //控制更新表单中的区域显示
                setisUpdateDisabled(true)
            }
            else{
                setisUpdateDisabled(false)
            }
            updateRef.current.setFieldsValue(item);//显示已有数据
        }, 0);
    }
    const updateForm=()=>{
        updateRef.current.validateFields().then(res=>{
            //与添加稍微有些不同，这是修改，要知道当前修改哪一项。所以使用新状态
            setdataSource(dataSource.map(item=>{
                if(item.id===curUpdate.id){
                    console.log(res);
                    return{
                        ...item,
                        ...res,
                        role: roleList.filter(item=>item.id===res.roleId)[0]    //角色名bug
                    }
                }
                return  item
            }),console.log(2))
            axios.patch(`/users/${curUpdate.id}`,res);

        })
        setisUpdateVisible(false);
        setisUpdateDisabled(!isUpdateDisabled)
    }
    return (
        <div>
            <Button type="primary" onClick={()=>setisVisible(true)}>添加用户</Button>
            <Modal title="添加用户" okText="确定" cancelText="取消" 
            visible={isVisible} 
            onOk={handleOk} 
            onCancel={handleCancel}>
                <UserForm isUpdate={false} regionList={regionList} roleList={roleList} ref={ref}></UserForm>
            </Modal>

            <Modal title="更新用户" okText="更新" cancelText="取消" 
            visible={isUpdateVisible} 
            onOk={()=>updateForm()} 
            onCancel={()=>{setisUpdateVisible(false);setisUpdateDisabled(!isUpdateDisabled)}}>
                <UserForm isUpdate={true} regionList={regionList} roleList={roleList} ref={updateRef} isUpdateDisabled={isUpdateDisabled}></UserForm>
            </Modal>

            <Table dataSource={dataSource} columns={columns}
                pagination={{
                    pageSize: 5
                }} 
                rowKey={item=>item.id}
                />
        </div>
    )
}
